package com.gzy.demo1.config;

import com.gzy.demo1.model.Account;
import com.gzy.demo1.resp.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
public class JWTUserDetailsService implements UserDetailsService {

    @Autowired
    AccountRepository accountRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Account account = accountRepository.findAccountByUsername(s);
        if (account == null) {
            throw  new UsernameNotFoundException("没有此用户");
        }
        UserDetails userDetails = User.builder()
                .username(account.getUsername())
                .password(account.getPassword())
                .roles(Arrays.asList(account.getRole()).toArray(new String[]{}))
                .build();

        return userDetails;
    }
}
